//
//  HaveWoundPictureVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/11/16.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "HaveWoundPictureVC.h"

#import "TopBackView.h"

#import "QiniuSDK.h"

#import "RootViewController.h"

#import "DynamicCollectionView.h"

#import "PicCollectionViewCell.h"

#import "DynamicCollectionViewCell.h"

#import "ScrollImageViewController.h"

@interface HaveWoundPictureVC ()
<
    UICollectionViewDelegate,
    UICollectionViewDataSource,
    UICollectionViewDelegateFlowLayout,
    UIImagePickerControllerDelegate,
    UINavigationControllerDelegate
>

@property (nonatomic, strong) NSMutableArray *postArr;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSIndexPath *currentIndexPath;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) NSMutableArray *imgArray;
@property (nonatomic, copy) NSString *token;
@property (nonatomic, strong) WKProgressHUD *hud;

@property (nonatomic, strong) TopBackView *topBackView;
@end

@implementation HaveWoundPictureVC
#pragma mark -
#pragma mark - Lazy
- (TopBackView *)topBackView {
    if (!_topBackView) {
       _topBackView = [[TopBackView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 64) title:@"上传带伤照片"];
        

        
        _topBackView.rightButton.hidden = YES;
        [_topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _topBackView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self.view addSubview:self.topBackView];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.view.backgroundColor = WhiteColor;
 
    self.imageArray = @[].mutableCopy;//存储url
    
    self.imgArray = @[].mutableCopy;;//存储key
    
    [self initDataSource];
    
    [self initTopView];
}

- (void)initDataSource {
    NSString *urlString = [NSString stringWithFormat:@"%@?waybillId=%@",attach_listpic,self.orderId];
    
    [Common requestWithUrlString:urlString contentType:application_json errorShow:YES finished:^(id responseObj)
    {
     
     if ([responseObj[@"deliverPics"] isEqual:[NSNull null]])
     {
         
         
     } else {
         
         if ([responseObj[@"data"] count] > 0) {
             
             for (int i = 0; i < [responseObj[@"data"] count]; i++) {
                 
                 NSString *string = [NSString stringWithFormat:@"%@",responseObj[@"data"][i][@"picURL"]];
                 
                 NSURL *url = [NSURL URLWithString:string];
                 [self.imageArray addObject: url];//存储url
                 [self.imgArray addObject:responseObj[@"data"][i][@"picKey"] ];//存储key

             }
         }
         [self.collectionView reloadData];
     }
 } failed:^(NSString *errorMsg) {
     NSLog(@"%@",errorMsg);
 }];
}


- (void)initTopView {
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64)];
    [self.view addSubview:self.scrollView];
    self.scrollView.contentSize = CGSizeMake(screenWidth, screenHeight + 1);
    self.scrollView.backgroundColor = GrayColor;
    
    
    UIView *firstV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, cellHeight)];
    firstV.backgroundColor = WhiteColor;
    [self.scrollView addSubview:firstV];
    
    
    UILabel *orderL = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 100 * kWidth, cellHeight)];
    orderL.text = @"带伤照片";
    orderL.textColor = littleBlackColor;
    orderL.font = Font(14);
    [firstV addSubview:orderL];
    
    [self initMiddleView];
    
    
}

- (void)initMiddleView{
    UIView *secondV = [[UIView alloc]initWithFrame:CGRectMake(0, cellHeight + 5* kHeight, screenWidth, 130 * kHeight)];
    secondV.backgroundColor = WhiteColor;
    [self.scrollView addSubview:secondV];
    
    
    UIImageView *imageV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"noPicture"]];
    imageV.frame = CGRectMake((screenWidth - 40)/2.0, 35 * kHeight, 40, 35);
    [secondV addSubview:imageV];
    
    UILabel *firstL = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(imageV.frame) , screenWidth, 40 * kHeight)];
    
   
    
    firstL.textColor = carScrollColor;
    firstL.font = Font(20);
    firstL.textAlignment = NSTextAlignmentCenter;
    [secondV addSubview:firstL];
    
    UILabel *secondL = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(firstL.frame) , screenWidth, 20 * kHeight)];
    secondL.font = Font(14);
    [secondV addSubview:secondL];
    secondL.textColor = carScrollColor;
    secondL.textAlignment = NSTextAlignmentCenter;
    
    
    if ([self.damageAudit integerValue] == 1) {
        firstL.text = @"您上传的照片正在审核";
        secondL.text = @"请耐心等待";

    } else if ([self.damageAudit integerValue] == 3)
    {
        firstL.text = @"您上传的照片审核未通过";
        secondL.text = @"请重新上传";
    }
    [self initCollectionView];
    
}

- (void)initCollectionView{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(80 * kHeight, 80 * kHeight);
//    layout.minimumInteritemSpacing = 40 * kHeight;
    layout.sectionInset = UIEdgeInsetsMake(10, 20, 10, 20);

    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 135 * kHeight + cellHeight, screenWidth, 200 * kHeight) collectionViewLayout:layout];
    [self.scrollView addSubview:self.collectionView];
    
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    
    //cell注册
    [self.collectionView registerClass:[PicCollectionViewCell class] forCellWithReuseIdentifier:@"PicCollectionViewCell"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    
    self.collectionView.backgroundColor = WhiteColor;
    
    
    if ([self.damageAudit integerValue] != 1) {
        
        [self initConfirmButtonWithView:self.collectionView];

        
    }
    
}



#pragma mark UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section{
    if ([self.damageAudit integerValue] == 1) {
        //审核中不能更改
        return self.imgArray.count;
        

    } else {
        
        return self.imgArray.count + 1;

    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PicCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PicCollectionViewCell" forIndexPath:indexPath];
    
  
    if ([self.damageAudit integerValue] == 1) {
        //审核中不能修改
    
    if (self.imageArray.count > 0) {
        
        [cell.heroImageView sd_setImageWithURL:self.imageArray[indexPath.row] placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
//            [self.imgArray addObject:image];
            if (error) {
                cell.heroImageView.image = [UIImage imageNamed:@"bad_picture"];
            }
            
            
        }];
    }else{
        cell.heroImageView.image = [UIImage imageNamed:@"car_style"];
        
    }
    } else {
        
        //审核未通过 可以修改
        if (self.imageArray.count > 0) {
            
            if (indexPath.row == self.imageArray.count ) {
                cell.heroImageView.image = [UIImage imageNamed:@"car_add"];
            } else {
                
                if ([self.imageArray[indexPath.row] isKindOfClass:[UIImage class]]) {
                    //数组中存储的是图片类型 直接赋值
                    cell.heroImageView.image = self.imageArray[indexPath.row];

                } else {
                
            [cell.heroImageView sd_setImageWithURL:self.imageArray[indexPath.row] placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                
                
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
                if (error) {
                    cell.heroImageView.image = [UIImage imageNamed:@"bad_picture"];
                }
                
            }];
            }
            }
        }else{
            cell.heroImageView.image = [UIImage imageNamed:@"car_add"];
            
        }

        
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
   
    if ([self.damageAudit integerValue] == 1) {
        // 不能修改
        ScrollImageViewController *scrollVC = [[ScrollImageViewController alloc]init];
        
        scrollVC.imageArr = _imageArray;
                
        [self.navigationController pushViewController:scrollVC animated:YES];
        
        
    } else {
        
        _currentIndexPath = indexPath;
        
        [self photoButton];

    }
}

- (void)initConfirmButtonWithView:(UIView *)view{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(18 , CGRectGetMaxY(view.frame) + 30, screenWidth - 36, Button_height);
    button.backgroundColor = YellowColor;
    [button setTitle:@"确认提交" forState:UIControlStateNormal];
    [button setTitleColor:WhiteColor forState:UIControlStateNormal];
    [button addTarget:self action:@selector(confirmButton) forControlEvents:UIControlEventTouchUpInside];
    button.layer.cornerRadius = 5;
    button.tag = 400;
    [self.scrollView addSubview:button];
}

- (void)confirmButton{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否确认提交" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                                    handler:^(UIAlertAction * _Nonnull action) {
        
        [self postPicture];
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                    handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)postPicture{
  //  Common *c = [[Common alloc]init];
//    NSString *urlString = [NSString stringWithFormat:@"%@attach/modify",Main_interface];
    
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:self.imgArray options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    
    NSDictionary *dic = @{@"waybillId":self.orderId,@"picKeys":jsonString};
    [[Common shared] afPostRequestWithUrlString:attach_modify parms:dic finishedBlock:^(id responseObj) {
        
        NSDictionary *dictionay = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
//        [WKProgressHUD popMessage:dictionay[@"message"] inView:self.view duration:1.5 animated:YES];
        
        if ([dictionay[@"success"] boolValue]) {
            
            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self backAction];
                
            });
            
            
        }
        
        
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];

}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
}




#pragma mark 获取照片
- (void)photoButton{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        [weakSelf getPictureFromCamera];
        
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf getPictureFromLibrary];
        
    }];
    
    
    UIAlertAction *action4 = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf deletePicture];
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
//    if (_currentIndexPath.row == 0) {
//        
//    }
    
    if (_currentIndexPath.row < self.imgArray.count ) {
        
        [alert addAction:action4];

    }
    
    
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark 拍照
-(void)getPictureFromCamera{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self  presentViewController:picker animated:YES completion:nil];
}

#pragma mark 从相册选取
-(void)getPictureFromLibrary{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self  presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark 删除
-(void)deletePicture{
    [self.imageArray removeObjectAtIndex:_currentIndexPath.row];
    [self.imgArray removeObjectAtIndex:_currentIndexPath.row];
    
    [self.collectionView reloadData];
}


#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        PicCollectionViewCell *cell = (PicCollectionViewCell *)[_collectionView cellForItemAtIndexPath:_currentIndexPath];
        cell.heroImageView.image = image;
        
        if (_currentIndexPath.row  != _imgArray.count) {
            
            [self.imageArray replaceObjectAtIndex:_currentIndexPath.row withObject:image];
            
        } else {
            [self.imageArray addObject:image];
        }
        
        self.hud  = [WKProgressHUD showInView:self.view withText:@"" animated:YES];
        
        //上传服务器
        [self getTokenFromQN];
        
    }];
}



#pragma mark 上传七牛
- (NSData *)getImageWith:(UIImage *)image{
    NSData *data = nil;
    if (UIImagePNGRepresentation(image)) {
        
        data = UIImageJPEGRepresentation(image, 0.1);
        
        
    } else {
        data = UIImagePNGRepresentation(image);
        
        
    }
    
    return data;
}

#pragma mark 从七牛获取Token
- (void)getTokenFromQN{
    
    [Common requestWithUrlString:qiniu_token contentType:application_json errorShow:YES finished:^(id responseObj) {
        if ([responseObj[@"success"] boolValue]) {
            
            self.token = responseObj[@"data"];
            
            PicCollectionViewCell *cell = (PicCollectionViewCell *)[_collectionView cellForItemAtIndexPath:_currentIndexPath];
            
            [self uploadImageToQNWithData:[self getImageWith:cell.heroImageView.image]];
            
            
        }
    } failed:^(NSString *errorMsg) {
        
        
        NSLog(@"%@",errorMsg);
    }];
    
    
    
}

- (void)uploadImageToQNWithData:(NSData *)data{
    
    QNUploadManager *upManager = [[QNUploadManager alloc]init];
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:data key:nil token:self.token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        
        if (_currentIndexPath.row  !=  _imgArray.count ) {
            //替换
            [self.imgArray replaceObjectAtIndex:_currentIndexPath.row withObject:resp[@"key"]];
            
        } else {
            //添加
            [self.imgArray addObject:resp[@"key"]];
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.collectionView reloadData];
            
        });
        
        
        [self.hud dismiss:YES];
        
    } option:uploadOption];
}



#pragma mark - 导航栏点击
- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}



@end
